package utils

import "github.com/gin-gonic/gin"

var ErrorCode = map[string]map[int]map[string]interface{}{
	"materiel_cls": {
		10: map[string]interface{}{"desc": "该生产订单已经有作业指令!不需要再次创建。", "status": 403}},
}



// 自定义错误对象
type BadRequst struct {
	Domain string `json:"domain"`
	Desc string `json:"desc"`
	StatusCode int `json:"status_code"`
	Detail interface{} `json:"detail"`
}


func NewBadRequst(resource string, errorCode int, kwargs interface{}) *BadRequst{
	errorInfo := ErrorCode[resource][errorCode]
	return &BadRequst{Domain: resource, Desc: errorInfo["desc"].(string), StatusCode: errorInfo["status"].(int),
		Detail: kwargs}
}

func OtherError(e string) *BadRequst{
	return &BadRequst{Domain: "default", Desc: "接口错误", StatusCode: 500,
		Detail: e}
}

func (b *BadRequst)ErrorMap(){}

func ErrHandler() gin.HandlerFunc  {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var Err *BadRequst
				if e,ok := err.(*BadRequst); ok {
					Err = e
				}else if e, ok := err.(error); ok {
					Err = OtherError(e.Error())
				}
				// 记录一个错误的日志
				c.JSON(Err.StatusCode,Err)
				return
			}
		}()
		c.Next()
	}
}
